﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcTest.Models;
using IBatisNet.DataMapper;
using MvcTest.Util;

namespace MvcTest.Controllers
{
    public class BoardController : Controller
    {

        IBoardRepository boardRepository;

        // GET: /Board/

        public ActionResult Index()
        {
            // XML 파일상의 쿼리를 호출하기 위해 iBATIS.NET은 Mapper 클래스를 제공한다.

            // 쿼리 결과는 Board 타입의 IList 형태로 반환된다.

            ViewData.Model = Mapper.Instance().QueryForList<Board>("SelectBoard", null);

            return View();
        }

        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult Read(string id )
        {
            
            ViewData.Model = Mapper.Instance().QueryForObject("ReadBoard", id);
            return View();
        }

        public ActionResult Write()
        {
            return View();
        }

        public ActionResult Edit(string id)
        {
            ViewData.Model = Mapper.Instance().QueryForObject("ReadBoard", id);
            return View();
        }
        
        [AcceptVerbs(HttpVerbs.Post)]
        [ValidateInput(false)]
        public ActionResult BoardProcess(Board collection) // 입력 부분
        {
            ValidateRequest = false;
            Board tmpBoard = new Board();
            
            tmpBoard.wr_id = Util.StringUtil.nullReturnEmpty(collection.wr_id);
            tmpBoard.bg_id = Util.StringUtil.nullReturnEmpty(collection.bg_id);

            tmpBoard.wr_subject = Util.StringUtil.nullReturnEmpty(collection.wr_subject);
            //tmpBoard.wr_content = HttpUtility.HtmlEncode(Util.StringUtil.nullReturnEmpty(collection["wr_content"]));
            //tmpBoard.wr_content = HttpUtility.HtmlEncode(Request.Form["wr_content"]);
            tmpBoard.wr_content = Server.HtmlEncode(collection.wr_content);
            tmpBoard.wr_password = Util.StringUtil.nullReturnEmpty(collection.wr_password);
            tmpBoard.wr_name = Util.StringUtil.nullReturnEmpty(collection.wr_name);
            


            if (tmpBoard.wr_id.ToString() == "" )
            {
                Mapper.Instance().Insert("InsertBoard", tmpBoard);
            } else {
                Mapper.Instance().Update("UpdateBoard", tmpBoard);
            }
            return RedirectToAction("Index");
        }

        public ActionResult Delete(string wr_id) // 삭제 부분
        {
            Mapper.Instance().Delete("DeleteBoard", wr_id);
            return RedirectToAction("Index");
        }

    }

   
}
